package controller

import (
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/errcode"
	"github.com/gin-gonic/gin"
	"net/http"
)

type BaseController struct{}

// Success
// 成果返回数据
func (c *BaseController) Success(ctx *gin.Context, data interface{}) {
	result := gin.H{
		"success":    true,
		"message":    "操作成功",
		"error_code": "",
		"data":       data,
	}

	ctx.JSON(http.StatusOK, result)
}

// Fail
// 失败返回数据数据
func (c *BaseController) Fail(ctx *gin.Context, code int, msg string) {
	result := map[string]interface{}{
		"success":    false,
		"message":    common.WrapError(msg),
		"error_code": code,
		"data":       nil,
	}

	ctx.JSON(http.StatusOK, result)
}

func (c *BaseController) GetErrCode(err error) int {
	grpcErr := rpc_client.GetGrpcError(err)
	errCode := errcode.COMMON_ERROR
	if grpcErr.GetCode() != 0 {
		errCode = grpcErr.GetCode()
	}
	return errCode
}

type HealthController struct {
	BaseController
}

func NewHealthController() *HealthController {
	return &HealthController{}
}

func (c *HealthController) RegisterRouter(g *gin.RouterGroup) {
	//心跳检测
	g.Any("/healthz", c.Health)
}

func (c *HealthController) Health(ctx *gin.Context) {
	c.Success(ctx, map[string]interface{}{
		"health": "健康检测ok(正常)",
	})
}
